import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import './index.scss'

import Cgnav from '../../components/category/cgnav'
import CgnavSub from '../../components/category/cgnavSub'
import CgList from '../../components/category/cglist'
import Cartbar from '../../components/category/cartbar'
import Authorize from '../../components/authorize/authorize'
import GoodsClose from '../../components/goodsClose'
import PopCartList from '../../components/cart/popCartList'

import { set as setGlobalData, get as getGlobalData } from '../../static/js/global_data'
import api from '../../service/api'
import base from '../../static/js/base'
import common from '../../service/common'

export default class Index extends Component {
    config = {
        navigationBarTitleText: '',
    }
    constructor() {
        super(...arguments)
        this.state = {
            shopInfo: getGlobalData('shopInfo'),
            tabActive: 0,
            navList: null,
            pageindex: 1,
            hasEd: false,
            hasGoodList: false,
            goodList: [],
            cartList: [], // 购物车缓存数据
            cartListState: false, // 购物车缓存数据隐藏
            cartNum: 0,
            price: {
                orderTotal: '0.00', // 实付款
                yhTotal: '0.00', // 优惠价格
                costTotal: '0.00', // 原价
                integralTotal: 0,
            },
            hasView: false,
            goodsInfo: null,
            goodsInfoType: 1, // 加入购物车缓存
            gid: '',
            countAddGood: true, // 加入购物车计算
        }
    }

    componentWillMount() { 
        Taro.setNavigationBarTitle({
            title: this.state.shopInfo.model.c_name
        })
        console.log(this.$router.params)
        const that = this
        console.log('cartData--------------------------')
            console.log(getGlobalData('cartData'))
        let cartData = getGlobalData('cartData')
        if(cartData){
            this.setState({
                cartList: cartData.cartList,
                cartNum: cartData.cartNum,
                price: cartData.price,
            })
        }
        
        base.showLoading()
        common.getUserInfo(that,function(data){
            that.setState({userInfo: data})
        })
        // 获取商品
        common.getCategory(that,function(category){
            that.state.cid = category[0].ID
            that.setGoodList(that)
            let cgnav = [],cgnav_str = ''; //一级分类
            let cgnavsub = [{'Name': '全部','ID': 'all'}],cgnavsub_str = ''; //二级分类
            category.map(function(item,i){
                cgnav_str = { ID: item.ID, name: item.name };
                cgnav.push(cgnav_str)
                if(i == 0){
                    item.sendcate.map(function(items,j){
                        if(items.type == 1){
                            cgnavsub_str = {ID: items.ID, Name: item.Name}
                            cgnavsub.push(cgnavsub_str)
                        }
                    })
                }
            })
            that.setState({
                cgnav: cgnav,
                cgnavId: cgnav[0].ID,
                cgnavsub: cgnavsub,
                cgnavsubId: cgnavsub[0].ID,
                category: category
            })
        })
    }
    // 一级分类
    tabNav(id){
        const that = this;
        if(id == that.state.cgnavId){return}
        let cgnavsub = [{'Name': '全部','ID': 'all'}],cgnavsub_str = ''; //二级分类
        this.state.category.map(function(item,i){
            if(item.ID == id){
                item.sendcate.map(function(items,j){
                    if(items.type == 1){
                        cgnavsub_str = {ID: items.ID, Name: items.Name}
                        cgnavsub.push(cgnavsub_str)
                    }
                })
            }
        })
        that.state.cid = id
        that.setState({
            hasGoodList: false,
            cgnavId: id,
            cgnavsub: cgnavsub,
            cgnavsubId: cgnavsub[0].ID,
            goodList: [],
            hasGoodList: false,
            hasEd: false,
            pageindex: 1,
        })
        base.showLoading()
        that.setGoodList(that)
    }
    // 切换分类
    tabNavSub(id){
        const that = this;
        that.state.cid = id == 'all' ? that.state.cgnavId : id;
        that.setState({
            cgnavsubId: id,
            goodList: [],
            hasGoodList: false,
            hasEd: false,
            pageindex: 1,
        })
        base.showLoading()
        that.setGoodList(that)
    }
    // 设置商品加入购物车的数量
    setGoodList(that){
        common.getGoodList(that,(goodList,hasEd) => {
            if(goodList){
                goodList.map((item) => {
                    item.N_NUM = 0;
                    that.state.cartList.map((items) => {
                        if(item.N_GB_ID == items.N_GB_ID){
                            item.N_NUM = items.nums
                        }
                    })
                })
            }
            that.setState({
                goodList: goodList,
                hasGoodList: true,
                hasEd: hasEd
            })
            Taro.hideLoading()
        })
    }
    // 获取购物车列表
    getCartNum(index,bNo,types){
        let env = process.env.TARO_ENV;
        if(env == 'alipay'){ //如果是支付宝，没有登陆先登陆
            const loginType = Taro.getStorageSync('loginType')
            if(!loginType){
                this.setState({ alipayAuthorize: true})
                return
            }
        }
        common.setCartList(this,'goodList',index,bNo,types,() => {
            if(types == 'add'){ // +
                this.state.cartNum++;
            }else if(types == 'minus'){ // -
                this.state.cartNum--;
            }
            this.setState({cartNum: this.state.cartNum})
        })
    }
    // 列表加载更多
    scrollToLowerList(){
        if(this.state.hasEd){return}
        this.state.pageindex++;
        base.showLoading()
        this.setGoodList(this)
    }
    // 切换规格
    getGoodsDatilsGG(myData){
        console.log(myData)
        const that = this;
        base.showLoading()
        common.getGoodDetailLvgg(that, that.state.goodsInfo, myData,(res) => {
            Taro.hideLoading()
            this.setState({
                goodsInfo: res.goods[0],
                // salemodel: this.isJsonStr(res.goods[0].salemodel) ? JSON.parse(res.goods[0].salemodel[0]) : null
            }, () => {
                this.changeShopCloseData()
            })
        })
    }
    changeShopCloseData() {
        /* 更新子组件的信息 */
        const { salemodel } = this.state;
        let d = {
            fPrice: salemodel ? salemodel.saledata.SalePrice : 0,
            integral: (salemodel && salemodel.SaleTypeNo == 5) ? salemodel.saledata.N_IntegralCount : 0,
        }
        this.shopCloseScope.setState(d)
    }
    //  authorize获取作用域
    getIsLogin(obj){
        const that = this;
        if(obj){
            if(obj.C_MB_NO){ 
                base.showLoading()
                common.getGoodDetail(that,getGlobalData('gid'),(res) => {
                    setGlobalData('gid', null)
                    Taro.hideLoading()
                    that.onChoose()
                })
            }else{
                this.isLogin = obj
            }
        }
    }
    // 点击弹出加入购物车弹窗
    onShowPopSpec(gid){
        setGlobalData('gid',gid)
        const that = this
        this.isLogin.isLogin(() => {
            base.showLoading()
            common.getGoodDetail(that,gid,(res) => {
                Taro.hideLoading()
                that.onChoose()
            })
        })
    }
    // 加入购物车
    onChoose(type, fPrice, joinData = null) {
         /* 由选择订单组件调起结算订单组件 */
         /* 传入拉起组件的方式----type */
         /* 优惠价格----fPrice */
         /* 积分 */
         const {goodsInfo,salemodel,lvgg} = this.state
         console.log(goodsInfo)
         const sType = salemodel ? salemodel.SaleTypeNo : 0
         let data = {
             type,//订单创建方式
             fPrice: salemodel ? salemodel.saledata.SalePrice : fPrice,
             integral: (salemodel && salemodel.SaleTypeNo == 5) ? salemodel.saledata.N_IntegralCount : 0,
             sType,
             lvgg,
             salemodel,
             joinData,//参加拼团的数据
         }
         if (sType == 5) {
             // 如果是积分
             data['fPrice'] = salemodel ? salemodel.saledata.ReallSalePrice : fPrice
         }
         if (type == 2) {
             this.setState({ isPayOne: 1 })
         } else {
             this.setState({ isPayOne: 0 })
         }
         console.log('onChoose-------------')
         console.log(data)
         this.shopCloseScope.showCut(data)
    }
    /* 获取结算订单组件作用域 */
    getShopClose(obj) {
        this.shopCloseScope = obj
    }
    /* 点击加入购物车确定 */
    onAddGoods(goodsInfo,num,salemodel){
        this.countGoodCart(goodsInfo,num,salemodel,'onAddGoods')
    }
    //  计算购物车数量，价格，商品列表的数量
    countGoodCart(goodsInfo,num,salemodel,countTypes,index){ // countTypes: true, 点击加入购物车 false 购物车加减
        let cartNum = 0;
        let price = {
            orderTotal: 0, // 实付款
            yhTotal: 0, // 优惠价格
            costTotal: 0, // 原价
            integralTotal: 0, // 总积分
        }
        if(salemodel){
            if(salemodel.SaleTypeNo == 5){// 积分
                goodsInfo.salePrice = parseFloat(salemodel.saledata.ReallSalePrice) 
                goodsInfo.saleIntegral = salemodel.saledata.N_IntegralCount
            }else if(salemodel.SaleTypeNo == 2){// 秒杀
                goodsInfo.salePrice = parseFloat(salemodel.saledata.SalePrice)
            }
        }
        goodsInfo.salePrice = goodsInfo.salePrice ? goodsInfo.salePrice : goodsInfo.SALE_PRICE
        goodsInfo.salemodel = salemodel
        if(countTypes == 'onAddGoods'){
            // 规格id
            let hasGoodsInfoID = this.state.cartList.some((item,i) => {
                return item.ID == goodsInfo.ID
            })
            if(hasGoodsInfoID){ // 购物车有当前规格商品
                this.state.cartList.map((item,i) => {
                    if(goodsInfo.ID == item.ID){
                        item.num = item.num + num
                    }
                })
            }else{ // 购物车无当前规格商品
                goodsInfo.num = num
                this.state.cartList.push(goodsInfo)
            }
        }
        let numTotal = 0
        this.state.cartList.map((item,i) => {
            if(countTypes != 'onAddGoods'){
                if(goodsInfo.ID == item.ID){
                    if(countTypes == 'add'){
                        if(item.num >= item.STOCK){
                            base.showToast('不能再加了！', 'none')
                            return
                        }
                        item.num++ 
                    }else {
                        item.num--
                    }
                } 
            }
            if(goodsInfo.N_GB_ID == item.N_GB_ID){
                numTotal += item.num
            }
            cartNum += item.num
            price.orderTotal += parseFloat(item.salePrice * item.num)
            price.costTotal += parseFloat(item.SALE_PRICE * item.num)
            if(item.saleIntegral){
                price.integralTotal += parseFloat(item.saleIntegral * item.num)
            }
        })
        this.state.cartList.map((item) => {
            if(item.num <= 0){
                this.state.cartList.splice(index,1)
            }
            if(goodsInfo.N_GB_ID == item.N_GB_ID){
                item.nums = numTotal
            }
        })
        this.state.goodList.map((item,i) => {
            if(goodsInfo.N_GB_ID == item.N_GB_ID){
                item.N_NUM = numTotal
            }
        })
        price.yhTotal = parseFloat(price.costTotal - price.orderTotal).toFixed(2)
        price.orderTotal = price.orderTotal.toFixed(2)
        price.costTotal = price.costTotal.toFixed(2)
        this.setState({
            cartList: this.state.cartList,
            cartNum,
            price,
            goodList: this.state.goodList,
            cartListState: this.state.cartList.length == 0 ? false : this.state.cartListState
        })
    }
    // 点击购物车图标显示购物车列表
    changeCartList(){
        this.setState({
            cartListState: !this.state.cartListState
        })
    }
    // 购物车里商品加减
    changeCartListNum(index,goodsInfo,bNo, types){
        let salemodel = goodsInfo.salemodel
        this.countGoodCart(goodsInfo,null,salemodel,types,index)
    }
    // 清空购物车
    clearCarList(){
        let {cartListState,goodList} = this.state
        goodList.map((item) => {
            item.N_NUM = 0
        })
        this.setState({
            cartListState: !cartListState,
            cartList: [],
            cartNum: 0,
            price: {
                yhTotal: '0.00',
                orderTotal: '0.00',
                costTotal: '0.00',
                integralTotal: 0,
            },
            goodList,
        })
    }
    // 点击去下单
    submitOrder(){
        let {peopleNum} = this.$router.params
        let cartData = {
            cartList: this.state.cartList,
            cartNum: this.state.cartNum,
            price: this.state.price,
        }
        this.setState({
            cartListState: false,
        })
        setGlobalData('cartData',cartData) 
        if(this.state.cartList.length > 0) {
            Taro.navigateTo({
                url: `/pages/subscribeSubmit/index?cartData=${JSON.stringify(cartData)}&peopleNum=${peopleNum}`
            })
        }else{
            base.showModal('请先选择商品！')
        }
    }

    render() {
        let {goodsInfo,cartList,cartListState} = this.state
        return (
            <View className='mainCategory bg-white'>
                {/* 一级分类 */}
                <View className='mainNav'>
                    <Cgnav cgnav={this.state.cgnav} cgnavId={this.state.cgnavId} onTabNav={this.tabNav.bind(this)}></Cgnav>
                </View>
                <View className='mainContent'>
                    {/* 二级分类 */}
                    <View className='mainNavSub'>
                        <CgnavSub cgnavsub={this.state.cgnavsub} cgnavsubId={this.state.cgnavsubId} onTabNavSub={this.tabNavSub.bind(this)}></CgnavSub>
                    </View>
                    {/* 分类商品列表 */}
                    <View className='mainList'>
                        <CgList goodList={this.state.goodList} hasEd={this.state.hasEd} hasGoodList={this.state.hasGoodList} onScrollToLowerList={this.scrollToLowerList.bind(this)} onShowPopSpec={this.onShowPopSpec.bind(this)}></CgList>
                    </View>
                </View>
                {/* 底部去下单 */}
                <View className={`cart-bar-list`}>
                    <Cartbar type='list' cartNum={this.state.cartNum} price={this.state.price} onChangeCartList={this.changeCartList.bind(this)} onSubmitOrder={this.submitOrder.bind(this)}></Cartbar>
                </View>
                {/* 结算订单组件 */}
                <GoodsClose onGetScope={this.getShopClose.bind(this)} goodsInfo={goodsInfo} goodsInfoType={this.state.goodsInfoType} onGetGoodsDatilsGG={this.getGoodsDatilsGG.bind(this)} onAddGoods={this.onAddGoods.bind(this)} />
                {/* 购物车列表 */}
                <PopCartList page='popupBottom' cartList={cartList} cartListState={cartListState} 
                    onClearCartList={this.clearCarList.bind(this)} 
                    onHideCartList={this.changeCartList.bind(this)}
                    onChangeCartNum={this.changeCartListNum.bind(this)}
                ></PopCartList>
                <Authorize page='onSetUserInfo' onSetUserInfo={this.getIsLogin.bind(this)}></Authorize>
            </View>
        )
    }
}

